//
//  I_Media.m
//  YunDongGym
//
//  Created by lqq on 2018/5/28.
//  Copyright © 2018年 lqq. All rights reserved.
//

#import "I_Media.h"
#import <AFNetworking.h>

@implementation I_Media
/**
 上传图片接口
 */
+ (NetworkTask *)upLoadImages:(NSArray *)images
                      success:(void(^)(NSArray *urls))successBlock
                      failure:(ErrorBlock)failureBlock
{
    
    __block int finishCount = 0;
    NSMutableArray *results = [NSMutableArray array];
    NSMutableArray *tasks = [NSMutableArray array];
    
    void(^uploadError)(NSError *error) = ^(NSError *error){
        for (NSURLSessionUploadTask *task in tasks) {
            [task cancel];
        }
        
        if (failureBlock) {
            failureBlock(error);
        }
    };
    
    void (^uploadSuccess)(NSString * url) = ^(NSString *url){
        finishCount ++;
        [results safeAddObject:url];
        if (finishCount == images.count && successBlock) {
            successBlock(results);
        }
    };
    
    for (int i = 1 ; i <= images.count ; i++) {
        UIImage *image = images[i - 1];
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@/gym-store-api/common/1.0.0/upload/file",KHOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            NSData *imageData = [UIImage compressImage:image toByte:1000*1000];
            [formData appendPartWithFileData:imageData name:@"multiFile" fileName:[NSString stringWithFormat:@"yd_%d.jpg",i] mimeType:@"image/jpg"];
            [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"mediumType"];
            [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"storeType"];
            [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"creatortype"];
#warning creator瞎写的
            [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"creator"];
            
        } error:nil];
        
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        
        NSURLSessionUploadTask *uploadTask;
        uploadTask = [manager
                      uploadTaskWithStreamedRequest:request
                      progress:^(NSProgress * _Nonnull uploadProgress) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                              
                          });
                      }
                      completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                          if (error) {
                              uploadError(error);
                          } else {
                              uploadSuccess(SAFE_VALUE_FOR_KEY(SAFE_VALUE_FOR_KEY(responseObject, @"data"), @"ossUrl"));
                          }
                      }];
        
        [uploadTask resume];
        
        [tasks addObject:uploadTask];
    }
    
    
    return nil;
}


///**
// 添加媒体(照片/视频)信息
// */
//+ (NetworkTask *)saveMediaWithMediaUrls:(NSArray *)mediaUrls objectId:(NSString *)objectId success:(void(^)(NSMutableArray *mediaList))successBlock failure:(ErrorBlock)failureBlock
//{
//    NSMutableArray *params = [NSMutableArray array];
//    for (int i = 0 ; i < mediaUrls.count; i++) {
//        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//        [dic setObject:SAFE_NIL_STRING(objectId) forKey:@"objectId"];
//        [dic setObject:RI.coach.coachId forKey:@"creatorId"];
//        [dic setObject:@(1) forKey:@"mediaType"];
//        [dic setObject:mediaUrls[i] forKey:@"mediaUrl"];
//        [dic setObject:@"YundongRecord" forKey:@"objectTable"];
//        [params addObject:dic];
//    }
//    return [NET POST:@"/gym-api/common/1.0.0/saveMedia" parameters:params criticalValue:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull resultObject) {
//        NSMutableArray *mediaList = [M_Media arrayOfModelsFromDictionaries:SAFE_VALUE_FOR_KEY(resultObject, @"data") error:nil];
//        if (successBlock) {
//            successBlock(mediaList);
//        }
//    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//        if (failureBlock) {
//            failureBlock(error);
//        }
//    }];
//}
/**
 删除媒体信息
 */
+ (NetworkTask *)deleteMediaWithMeidaId:(NSString *)mediaId success:(void(^)(void))successBlock failure:(ErrorBlock)failureBlock
{
    return [NET POST:@"/gym-api/common/1.0.0/deleteMedia" parameters:@{@"mediaId":SAFE_NIL_STRING(mediaId)} criticalValue:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull resultObject) {
        if (successBlock) {
            successBlock();
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}

/**
 请求用户训练图片
 */
+ (NetworkTask *)requestMemberRecordPhotoAlbumWithMemberId:(NSString *)memberId
                                                   success:(void(^)(NSMutableArray *list))successBlock failure:(ErrorBlock)failureBlock
{
    return [NET POST:@"/gym-api/member/1.0.0/myRecordMediaDate" parameters:@{@"memberId":SAFE_NIL_STRING(memberId)} criticalValue:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull resultObject) {
        NSMutableArray *list = [M_MediaDate arrayOfModelsFromDictionaries:SAFE_VALUE_FOR_KEY(resultObject, @"data") error:nil];
        if (successBlock) {
            successBlock(list);
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
}


@end
